
// 动态选择框
$(function(){
    //动态选择框，上下级选中状态变化
    $('input.checkbox-parent').on('change', function(){
        var dataid = $(this).attr("dataid");
        $('input[dataid^=' + dataid + '-]').prop('checked', $(this).is(':checked'));
    });
    $('input.checkbox-child').on('change', function(){
        var dataid = $(this).attr("dataid");
        dataid = dataid.substring(0, dataid.lastIndexOf("-"));
        var parent = $('input[dataid=' + dataid + ']');
        if($(this).is(':checked')){
            parent.prop('checked', true);
            //循环到顶级
            while(dataid.lastIndexOf("-") !== 2){
                dataid = dataid.substring(0, dataid.lastIndexOf("-"));
                parent = $('input[dataid=' + dataid + ']');
                parent.prop('checked', true);
            }
        }else{
            //父级
            if($('input[dataid^=' + dataid + '-]:checked').length === 0){
                parent.prop('checked', false);
                //循环到顶级
                while(dataid.lastIndexOf("-") !== 2){
                    dataid = dataid.substring(0, dataid.lastIndexOf("-"));
                    parent = $('input[dataid=' + dataid + ']');
                    if($('input[dataid^=' + dataid + '-]:checked').length === 0){
                        parent.prop('checked', false);
                    }
                }
            }
        }
    });
});

// 清除设置按钮点击事件
function reset() {
    $("table").reset();
}

/**
 * 异步获取学院的班级
 * @param college
 */
function getClassesAjax(college) {
    lightyear.loading("show");
    $.ajax({
        type: "GET",
        url: "/Task/class/" + college,
        dataType: "json",
        success: function (data, status) {
            lightyear.loading("hide");
            console.log(data)
            if (status === "success") {
                if (data.code === 200){
                    setClasses(college, data.data.class);
                } else{
                    console.log("后端拒绝")
                    lightyear.notify(data.msg, 'danger', 3000);
                }
            }else{
                lightyear.notify('网络不可用，请稍候再试！！！', 'danger', 3000);
            }
        },
        error: function (xhr, errorText, errorType) {
            lightyear.loading("hide");
            lightyear.notify('服务器错误，请稍后再试~', 'danger', 2000);
        }
    })
}

/**
 * 设置并将班级添加到对应的学院下方班级
 * @param college
 * @param classes
 */
function setClasses(college, classes) {

    let html = "<tr id='class-"+college+"' class='show'><td class=\"p-l-40\">\n";
    $.each(classes, function (i, c) {
        html += "   <label class=\"lyear-checkbox checkbox-primary checkbox-inline\">\n" +
            "       <input name=\"rules[]\" type=\"checkbox\" class=\"checkbox-child\" dataid=\"id-1-"+ college +"-"+ c.cid +"\" value=\""+ c.cname +"\">\n" +
            "       <span> "+c.cname+"</span>\n" +
            "   </label>\n"
    });
    html += "</td></tr>"

    $("#"+college).after(html)
}

/**
 * 显示或隐藏学院的班级
 * @param college
 */
function showCollege(college) {
    console.log("准备显示学院的班级", $("#class-"+college))
    if ($("#class-"+college).length !== 0){
        console.log("班级已存在")
        if ($("#class-"+college).attr("class") === 'show') {
            console.log("班级已存在")
            $("#class-"+college).removeClass("show")
            $("#class-"+college).addClass("hide")
            return false;
        } else{
            $("#class-"+college).removeClass("hide")
            $("#class-"+college).addClass("show")
            return true;
        }
    }else{
        console.log("班级不存在")
        getClassesAjax(college);
    }
}

/**
 * 获取发布范围
 * @returns {string|[]}
 */
function checkChecked(){
    // 选中的学院和班级
    let collegeList = [];
    let checkedList = [];
    // 先检查ALL选项
    if ($("#check-all").prop("checked")){
        return "all";
    }
    // 先检查学院选项
    $("input.checkbox-parent.checkbox-child").each(function (i, c) {
        let college = $(c).prop("value");
        if ($(c).prop("checked")){
            checkedList.push({"college":college, "value":"all"});
        }else {
            let dataid = $(c).attr("dataid");
            let classe = {"college":college, "value":[]};
            $('input[dataid^=' + dataid + '-]').each(function (j, cla) {
                if ($(cla).prop("checked"))
                    classe.value.push($(cla).prop("value"));
            });
            checkedList.push(classe);
        }
    });

    $.each(checkedList, function (i, v) {
        if (v.value.length > 0 || v.value === "all"){
            collegeList.push(v)
        }
    })

    console.log("打印选择结果",collegeList);
    return collegeList;
}


function saveTaskAjax(url, taskName, taskTemplate, taskStart, taskEnd, taskRange) {
    lightyear.loading('show');
    $.ajax({
        type: "POST",
        url: "/Task/" + url,
        dataType: "json",
        data: {
            "taskName":taskName,
            "taskTemplate": taskTemplate,
            "taskStart": taskStart,
            "taskEnd": taskEnd,
            "taskRange": taskRange
        },
        success: function (data, status) {
            console.log(data)
            lightyear.loading('hide');
            if (status === "success") {
                if (data.code === 200){
                    lightyear.notify('成功了，页面即将自动跳转~', 'success', 300);
                    setTimeout(function () {
                        location.href = "/Task/List";
                    }, 3000)

                } else{
                    console.log("后端拒绝服务~")
                    lightyear.notify(data.msg, 'danger', 3000);
                }
            }else{
                console.log("网络问题")
                lightyear.notify('网络不可用，请稍候再试！！！', 'danger', 3000);
            }
        },
        error: function (xhr, errorText, errorType) {
            lightyear.loading('hide');
            lightyear.notify('服务器错误，请稍后再试~', 'danger', 2000);
        }
    });


}



function saveTask() {
    // $type 提示类型:'info', 'success', 'warning', 'danger'
    // $icon 图标，例如：'fa fa-user' 或 'glyphicon glyphicon-warning-sign'
    let taskName = $("#taskName").val();
    if (taskName.length === 0){
        lightyear.notify("请填写任务名称", "danger");
        return false;
    }

    let template = $("#template").val();
    if (template === '0'){
        lightyear.notify("请选择填报模板", "danger");
        return false;
    }

    let start_time = $("#start_time").val();
    if (start_time === ''){
        lightyear.notify("请填写填报开始时间", "danger");
        return false;
    }
    console.log(start_time)

    let end_time = $("#end_time").val();
    if (end_time === ''){
        lightyear.notify("请填写填报结束时间", "danger");
        return false;
    }
    let range = checkChecked()
    if (range.length === 0){
        lightyear.notify("请至少选择一个班作为发布对象", "danger")
        return false;
    }

    // 转换时间
    start_time = start_time.replace("T"," ");
    end_time = end_time.replace("T", " ")
    // JSON to String
    range = JSON.stringify(range);
    let taskId = $("#taskId").attr("data");

    console.log("任务名称", taskName);
    console.log("填报模板", template);
    console.log("任务开始时间", start_time);
    console.log("任务结束时间", end_time);
    console.log("发布范围", range);

    if (taskId === '-999999'){
        saveTaskAjax('Save', taskName, template, start_time, end_time, range)
        // saveTaskAjax(url, taskName, taskTemplate, taskStart, taskEnd, taskRange, taskId)
    }else{
        saveTaskAjax('Edit/'+taskId, taskName, template, start_time, end_time, range)
    }
}

